package com.sicheng.lc.周赛.分类.dfs记忆化;

import java.util.ArrayDeque;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/7/14 23:00
 */
public class 统计子岛屿 {
    //https://leetcode.cn/problems/count-sub-islands/
    int m, n;
    int res;
    static ArrayDeque<int[]> deque = new ArrayDeque<>(500);

    public int countSubIslands(int[][] grid1, int[][] g) {
        m = grid1.length;
        n = grid1[0].length;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (g[i][j] == 1)
                    g[i][j] += grid1[i][j];
            }
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (g[i][j] == 2 && bfs(g, i, j)) {
                    res++;
                }
            }
        }

        return res;
    }

    int[][] d = {
            {0, 1}, {1, 0}, {-1, 0}, {0, -1}
    };

    private boolean bfs(int[][] g, int i, int j) {
        g[i][j] = 0;
        deque.offer(new int[]{i, j});
        boolean res = true;
        while (!deque.isEmpty()) {
            int[] p = deque.poll();
            for (int[] dd : d) {
                int x = p[0] + dd[0];
                int y = p[1] + dd[1];
                if (x >= 0 && x < m && y >= 0 && y < n && g[x][y] > 0) {
                    if (g[x][y] == 1) {
                        res = false;
                        continue;
                    }
                    g[x][y] = 0;
                    deque.offer(new int[]{x, y});
                }
            }
        }

        return res;
    }
}
